package com.websocket;

import com.alibaba.fastjson.JSON;
import com.common.converter.FlightRealTimeDataConverter;
import com.entity.FlightData;
import com.entity.FlightRealTimeData;
import com.common.enums.MAV_STATE;
import com.mapper.influx.FlightRealTimeDataMapper;
import com.utils.CustomModeHelper;
import com.utils.DroneConnection;
import io.dronefleet.mavlink.Mavlink2Message;
import io.dronefleet.mavlink.MavlinkConnection;
import io.dronefleet.mavlink.MavlinkMessage;
import io.dronefleet.mavlink.common.Attitude;
import io.dronefleet.mavlink.common.HomePosition;
import io.dronefleet.mavlink.common.LocalPositionNed;
import io.dronefleet.mavlink.common.VfrHud;
import io.dronefleet.mavlink.minimal.Heartbeat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.text.SimpleDateFormat;

/**
 * @className: MavlinkMessageHandler
 * @description: TODO 类描述
 * @author: Kuangkeli
 * @date: 2024/07/02 22:23
 **/
@Component
public class MavlinkMessageHandler {

    private final MessageWebSocketHandler webSocketHandler;
    private Thread messageHandlingThread;

    // 全局变量
    private HomePosition homePosition = null;

    private FlightData flightData = new FlightData();

    @Autowired
    private FlightRealTimeDataMapper flightRealTimeDataMapper;
    private boolean isRecord = false;
    private String timeId;
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

    @Autowired
    public MavlinkMessageHandler(MessageWebSocketHandler webSocketHandler) throws IOException {
        this.webSocketHandler = webSocketHandler;
    }

    @PostConstruct
    public void init() throws IOException {

        messageHandlingThread = new Thread(() -> {
            try {
                handleMessages();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        messageHandlingThread.start();
    }

    public void handleMessages() throws IOException {
        MavlinkConnection connection = DroneConnection.getInstance();
        MavlinkMessage message;
        Thread sendMessageThread = new Thread(() -> {
            try {
                int count = 0;
                while (true){
                    webSocketHandler.sendMessage(JSON.toJSONString(flightData));
                    if(isRecord){
                        if(flightData.getSystemStatusText().equals("未解锁")){
                            isRecord = false;
                            FlightRealTimeData flightRealTimeData
                                    = FlightRealTimeDataConverter.INSTANCE.flightDataToFlightRealTimeData(flightData);
                            flightRealTimeData.setTimeId(timeId);
                            flightRealTimeDataMapper.save(flightRealTimeData);
                            count = 0;
                        }
                        else {
                            FlightRealTimeData flightRealTimeData
                                    = FlightRealTimeDataConverter.INSTANCE.flightDataToFlightRealTimeData(flightData);
                            flightRealTimeData.setTimeId(timeId);
                            if(count % 1 == 0){
                                flightRealTimeDataMapper.save(flightRealTimeData);
                            }
                            count++;
                        }
                    }
                    else{
                        if("解锁".equals(flightData.getSystemStatusText())){
                            isRecord = true;
                            timeId = simpleDateFormat.format(System.currentTimeMillis());
                        }
                    }
                    Thread.sleep(100);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        sendMessageThread.start();
        while ((message = connection.next()) != null) {
            if (message instanceof Mavlink2Message) {
                Mavlink2Message message2 = (Mavlink2Message) message;
                if (message2.isSigned()) {
                    if (message2.validateSignature("mySecretKey".getBytes())) {
                        // 签名有效
                    } else {
                        // 签名验证失败
                    }
                }
            }
            if (message.getPayload() instanceof Heartbeat) {
                MavlinkMessage<Heartbeat> heartbeatMessage = (MavlinkMessage<Heartbeat>) message;
                flightData.setCustomModeText(CustomModeHelper.getCustomModeState(heartbeatMessage.getPayload().customMode()));
                flightData.setSystemStatusText(MAV_STATE.fromValue(heartbeatMessage.getPayload().systemStatus().value()).getDescription());
            } else if (message.getPayload() instanceof LocalPositionNed) {
                LocalPositionNed localPositionNed = (LocalPositionNed) message.getPayload();
                flightData.setX(localPositionNed.x());
                flightData.setY(localPositionNed.y());
                flightData.setZ(String.format("%.2f", -localPositionNed.z()));
            } else if (message.getPayload() instanceof HomePosition) {
                homePosition = (HomePosition) message.getPayload();
            } else if (message.getPayload() instanceof Attitude) {
                Attitude attitude = (Attitude) message.getPayload();
                flightData.setYaw(attitude.yaw());
                flightData.setRoll(attitude.roll());
                flightData.setPitch(attitude.pitch());
            } else if (message.getPayload() instanceof VfrHud){
                VfrHud vfrHud = (VfrHud)message.getPayload();
                flightData.setGroundSpeed(String.format("%.2f",vfrHud.groundspeed()));
            }
        }
    }

    // 返回homePosition值的接口方法
    public HomePosition getHomePosition() {
        return homePosition;
    }

    public void setTimeId(String timeId) {
        this.timeId = timeId;
    }
}